package com.poobo.controller;

//add by hxh 20160517
//import java.io.File;
import java.io.FileWriter;
//import java.io.FileOutputStream;



import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;



//import org.dom4j.Document;
//import org.dom4j.DocumentHelper;
//import org.dom4j.Element;
//import org.dom4j.io.OutputFormat;
//import org.dom4j.io.XMLWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.zxing.common.StringUtils;
import com.poobo.aop.SystemCtrLo4jAop;
import com.poobo.condiction.ResourcesConfigCondiction;
import com.poobo.entity.TbConfigList;
import com.poobo.entity.TbEqGamesInfo;
import com.poobo.entity.TbEquipment;
import com.poobo.entity.TbEquipmentConfiglist;
import com.poobo.entity.TbResources;
import com.poobo.entity.TbResourcesConfig;
import com.poobo.service.IConfigListService;
import com.poobo.service.IResourcesConfigService;
import com.poobo.service.IResourcesService;
import com.poobo.util.pager.Page;
import com.poobo.util.property.PropertyUtil;
import com.poobo.util.str.StrUtil;

@Controller
@RequestMapping("resourcesConfig")
public class ResourcesConfigCtr {
	@Autowired
	private IResourcesConfigService resourcesConfigService;
	@Autowired
	private IResourcesService resourcesService;
	@Autowired 
	private IConfigListService configListService;
		
	/**
	 * 跳转资源配置列表
	 * @param request
	 * @param resourcesConfig
	 * @param page
	 * @return
	 */
	@RequestMapping("toResourcesConfigPage")
	public String toResourcesConfigPage(HttpServletRequest request,ResourcesConfigCondiction resourcesConfig,String weekName,Page page){
		if( resourcesConfig.getConfigName() != null ){
			request.setAttribute("configName", resourcesConfig.getConfigName());
		}
		if( StrUtil.isNotNull(weekName) ){
			if (weekName.contains("一") || weekName.contains("1")) {
				resourcesConfig.setWeek(1);
			}else if (weekName.contains("二") || weekName.contains("2")) {
				resourcesConfig.setWeek(2);
			}else if (weekName.contains("三") || weekName.contains("3")) {
				resourcesConfig.setWeek(3);
			}else if (weekName.contains("四") || weekName.contains("4")) {
				resourcesConfig.setWeek(4);
			}else if (weekName.contains("五") || weekName.contains("5")) {
				resourcesConfig.setWeek(5);
			}else if (weekName.contains("六") || weekName.contains("6")) {
				resourcesConfig.setWeek(6);
			}else if (weekName.contains("日") || weekName.contains("0")) {
				resourcesConfig.setWeek(0);
			}
			request.setAttribute("weekName", weekName);
		}
		page = resourcesConfigService.queryResourcesConfigPage(resourcesConfig, page);
		request.setAttribute("pageNo", page.getPageNo());
		request.setAttribute("pageNum", page.getPageNum());
		request.setAttribute("pageSize", page.getPageSize());
		request.setAttribute("resourcesConfigs", page.getPageList());
		List<Map<String, Object>> list = (List<Map<String, Object>>) page.getPageList();
		Map<String, List<Map<String, Object>>> map =  
				new HashMap<String, List<Map<String, Object>>>();
		Map<String, Object> temp = null;
		String temp_key = null;
		for( int i=0; i < list.size(); i++ ){
			temp = list.get(i);
			temp_key = temp.get("configName")+"";
//			temp_key = temp.get("configId")+"&"+temp.get("configName");
			if(map.containsKey(temp_key)){
				map.get(temp_key).add(temp);
			}
			else{
				List<Map<String, Object>> r_list = new ArrayList<Map<String, Object>>();
				r_list.add(temp);
				map.put(temp_key, r_list);
			}
		}
		request.setAttribute("map", map);
		return "resourcesConfig/resources_config";
	}
	/**
	 * 跳转到新增页面
	 * @param request
	 * @return
	 */
	@RequestMapping("toSaveResourcesConfig")
	public String toSaveConfigList(HttpServletRequest request){
		List<TbConfigList> configLists = configListService.queryAll();
		List<TbResources> resources = resourcesService.queryAll();
		request.setAttribute("configLists", configLists);
		request.setAttribute("resources",resources );
		return "resourcesConfig/save_resources_config";
	}
	/**
	 * 新增资源配置
	 * @param resourcesConfig
	 * @return
	 */
	@RequestMapping("saveResourcesConfig")
	@SystemCtrLo4jAop(description="新增资源配置")
	public String saveResourcesConfig( TbResourcesConfig resourcesConfig ){
		if( resourcesConfig.getResourcesId() != null && resourcesConfig.getSeconds()==null ){
			Short type = resourcesService.queryResourcesById(resourcesConfig.getResourcesId()).getType();
			if( type==2 ){
				resourcesConfig.setSeconds(3);
			}else {
				resourcesConfig.setSeconds(0);
			}
		}
		if(resourcesConfig.getResourcesId() == null){
			resourcesConfig.setSeconds(0);
		}
		if( StrUtil.isNull(resourcesConfig.getIsSpecial()) ){
			resourcesConfig.setIsSpecial("N");
		}
		resourcesConfigService.saveResourcesConfig(resourcesConfig);
		try {
			TbConfigList configList = configListService.queryConfigListById(resourcesConfig.getConfigId());
			String flag = generateTxt( configList );
			System.out.println(flag);
		} catch (Exception e) {
			e.getStackTrace();
		}
		return "redirect:/resourcesConfig/toResourcesConfigPage.html";
	}
	/**
	 * 编辑资源配置
	 * @param resourcesConfig
	 * @return
	 */
	@RequestMapping("editResourcesConfig")
	@SystemCtrLo4jAop(description="新增资源配置")
	public String editResourcesConfig( TbResourcesConfig resourcesConfig ){
		if( resourcesConfig.getResourcesId() != null && (resourcesConfig.getSeconds()==null || resourcesConfig.getSeconds()==0 ) ){
			Short type = resourcesService.queryResourcesById(resourcesConfig.getResourcesId()).getType();
			if( type==2 ){
				resourcesConfig.setSeconds(3);
			}else {
				resourcesConfig.setSeconds(0);
			}
		}
		if(resourcesConfig.getResourcesId() == null){
			resourcesConfig.setSeconds(0);
		}
		if( StrUtil.isNull(resourcesConfig.getIsSpecial()) ){
			resourcesConfig.setIsSpecial("N");
		}
		resourcesConfigService.saveResourcesConfig(resourcesConfig);
		try {
			TbConfigList configList = configListService.queryConfigListById(resourcesConfig.getConfigId());
			String flag = generateTxt( configList );
			System.out.println(flag);
		} catch (Exception e) {
			e.getStackTrace();
		}
		return "redirect:/resourcesConfig/toResourcesConfigPage.html";
	}
	/**
	 * 跳转编辑页面
	 * @param request
	 * @param resourcesConfig
	 * @param configList
	 * @param resources
	 * @return
	 */
	@RequestMapping("toEditResourcesConfig")
	public String toEditConfigList(HttpServletRequest request,TbResourcesConfig resourcesConfig,
			TbConfigList configList,TbResources resources){
		Integer id = Integer.parseInt(request.getParameter("resourcesConfigId"));
		resourcesConfig = resourcesConfigService.queryResourcesConfigById(id);
		request.setAttribute("configLists", configListService.queryAll() );
		request.setAttribute("resourcesList",resourcesService.queryAll() );
		request.setAttribute("configList", configListService.queryConfigListById(resourcesConfig.getConfigId()));
		request.setAttribute("resourcesConfig", resourcesConfig);
		if( resourcesConfig.getResourcesId() != null ){			
			request.setAttribute("resources", resourcesService.queryResourcesById(resourcesConfig.getResourcesId()));
		}
		
		return "resourcesConfig/edit_resources_config";
	}
	/**
	 * 根据ID删除单个资源配置
	 * @param request
	 * @return
	 */
	@RequestMapping("deleteById")
	@SystemCtrLo4jAop(description="删除单个资源配置")
	public String deleteById( HttpServletRequest request ){
		Integer id = Integer.parseInt(request.getParameter("ResourcesConfigId"));
		try {
			TbResourcesConfig resourcesConfig = resourcesConfigService.queryResourcesConfigById(id);
			Integer configId = resourcesConfig.getConfigId();
			resourcesConfigService.deleteResourcesConfigById(id);
			TbConfigList configList = configListService.queryConfigListById(configId);
			String flag = generateTxt( configList );
			System.out.println(flag);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "redirect:/resourcesConfig/toResourcesConfigPage.html";
	}
	@RequestMapping("deleteByIds")
	@SystemCtrLo4jAop(description="批量删除资源配置")
	public String deleteByIds( HttpServletRequest request ){
		String ids = request.getParameter("ids");
		String[] idss = ids.split(",");
		Integer id = null;
		try {
			for (String idStr : idss) {
				id = Integer.parseInt(idStr);
				resourcesConfigService.deleteResourcesConfigByConfigListId(id);
				TbConfigList configList = configListService.queryConfigListById(id);
				String flag = generateTxt( configList );
				System.out.println(flag);
			}
		} catch (Exception e) {
			e.getStackTrace();
		}
		return "redirect:/resourcesConfig/toResourcesConfigPage.html";
	}
	
	/**
	 * 复制资源配置列表
	 * @param request
	 * @return
	 */
	@RequestMapping("copyConfigListByIds")
	@SystemCtrLo4jAop(description="复制资源配置列表")
	public String copyConfigListByIds( HttpServletRequest request ){
		String ids = request.getParameter("ids");
		String[] idss = ids.split(",");
		Integer id = null;
		try {
			if (idss.length>0) {
				id = Integer.parseInt(idss[0]);
				String configName = resourcesConfigService.copyResourcesConfigByConfigListId(id);
				TbConfigList configList = configListService.queryConfigListByName(configName);
				List<TbResourcesConfig> resourcesConfigs = resourcesConfigService.queryResourcesConfigByConfigListId(id);
				TbResourcesConfig rc = null;
				for (int i = 0; i < resourcesConfigs.size(); i++) {
					rc = new TbResourcesConfig();
					rc.setActionDate(resourcesConfigs.get(i).getActionDate());
					rc.setConfigId(configList.getId());
					rc.setDateCompany(resourcesConfigs.get(i).getDateCompany());
					rc.setDayFive(resourcesConfigs.get(i).getDayFive());
					rc.setDayFour(resourcesConfigs.get(i).getDayFour());
					rc.setDayOne(resourcesConfigs.get(i).getDayOne());
					rc.setDayThree(resourcesConfigs.get(i).getDayThree());
					rc.setDayTwo(resourcesConfigs.get(i).getDayTwo());
					rc.setDisplayOrder(resourcesConfigs.get(i).getDisplayOrder());
					rc.setEndDate(resourcesConfigs.get(i).getEndDate());
					rc.setIsAlone(resourcesConfigs.get(i).getIsAlone());
					rc.setIsLive(resourcesConfigs.get(i).getIsLive());
					rc.setIsSpecial(resourcesConfigs.get(i).getIsSpecial());
					rc.setResourcesId(resourcesConfigs.get(i).getResourcesId());
					rc.setSeconds(resourcesConfigs.get(i).getSeconds());
					rc.setUrl(resourcesConfigs.get(i).getUrl());
					rc.setWeek(resourcesConfigs.get(i).getWeek());
					resourcesConfigService.saveResourcesConfig(rc);
				}
				String flag = generateTxt( configList );
				System.out.println(flag);
			}
		} catch (Exception e) {
			e.getStackTrace();
		}
		return "redirect:/resourcesConfig/toResourcesConfigPage.html";
	}
	
	
	/**
	 * 根据资源ID下拉列获取资源
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("searchResources")
	@ResponseBody
	public String searchResources( HttpServletRequest request,HttpServletResponse response ){
		response.setCharacterEncoding("utf-8");
		String type = request.getParameter("type");
		String data = "";
		List<TbResources> list = resourcesService.queryRsourcesByType(Short.parseShort(type));
		if( list != null && list.size()>0 ){			
			for (int i = 0; i < list.size(); i++) {
				TbResources resources = list.get(i);
				if( i == list.size()-1 ){
					data += resources.getId() + "," + resources.getName();
				}else{
					data += resources.getId() + "," + resources.getName() + "&";
				}
			}
		}
		try {
			response.getWriter().write(data);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	//生成txt
	public String generateTxt( TbConfigList configList ){
		Integer configListId = configList.getId();
		String flag = null;
		configList = configListService.queryConfigListById(configListId);
		List<TbResourcesConfig> resourcesConfigs = resourcesConfigService.queryResourcesConfigByConfigListId(configListId);
		try {
			String path = PropertyUtil.configProperty.getProperty("resource_disk_base_path") + File.separator + PropertyUtil.configProperty.getProperty("resource_ConfigListTxt");
			File dir = new File(path);
			if (!dir.exists()) {
				dir.mkdirs();
			}
			File file = new File( path + File.separator + configListId + ".txt" );
			if (!file.exists()) {
				file.createNewFile();
			}else{
				file.delete();
			}
			PrintWriter pw = new PrintWriter(file);
			String fRow="";
			StringBuffer firstRow = new StringBuffer();
			int index = 0;
			int total = 0;
			for( int j=0; j<resourcesConfigs.size(); j++ ){
				if("Y".equals(resourcesConfigs.get(j).getIsSpecial()) || "Y".equals(resourcesConfigs.get(j).getIsLive())){
					index = 1;
				}else{
					total++;
				}
			}
			if( index==1 ){
				firstRow.append("Y|");
				for( int k=0; k<resourcesConfigs.size(); k++ ){
					if("Y".equals(resourcesConfigs.get(k).getIsSpecial())){
						String one = resourcesConfigs.get(k).getDayOne().toString().substring(0, 10);
						String two = resourcesConfigs.get(k).getDayTwo().toString().substring(0, 10);
						String three = resourcesConfigs.get(k).getDayThree().toString().substring(0, 10);
						String four = resourcesConfigs.get(k).getDayFour().toString().substring(0, 10);
						String five = resourcesConfigs.get(k).getDayFive().toString().substring(0, 10);
						if( !one.equals("2000-01-01") ){
							firstRow.append( one + "|" );
						}
						if( !two.equals("2000-01-01") ){
							firstRow.append( two + "|" );
						}
						if( !three.equals("2000-01-01") ){
							firstRow.append( three + "|" );
						}
						if( !four.equals("2000-01-01") ){
							firstRow.append( four + "|" );
						}
						if( !five.equals("2000-01-01") ){
							firstRow.append( five + "|" );
						}
					}
				}
				firstRow.append("&nextline&");
				if(firstRow.indexOf("|&nextline&")!=-1){
					fRow = firstRow.substring(0,firstRow.length()-11);
					fRow = fRow + "&nextline&";
				}
			}else {
				firstRow.append("N&nextline&");
				fRow = firstRow.toString();
			}
			//第一行为列表的资源数量
			pw.print(total + "|" + fRow);
			pw.println();
			
			int index2 = 0 ;
			String row2 = "";
			StringBuffer row2a = new StringBuffer();
			for( int k=0; k<resourcesConfigs.size(); k++ ){
				if(resourcesConfigs.get(k).getIsLive().equals("Y")){
					index2++ ;
					String date1 = resourcesConfigs.get(k).getActionDate().toString().substring(0, 19);
					String date2 = resourcesConfigs.get(k).getEndDate().toString().substring(0, 19);
					if(index==1){						
						row2a.append(date1 +"|"+ date2 +"|"+resourcesConfigs.get(k).getUrl()+"&nextline&");
					}
				}
			}
			if( index2 > 0 ){
				row2 = "Y|"+row2a.toString();
			}else{
				row2 = "N&nextline&";
			}
			//第二行为列表的资源数量
			pw.print(row2);
			pw.println();
			
			for( int i=0; i<resourcesConfigs.size(); i++ ){
				if("N".equals(resourcesConfigs.get(i).getIsSpecial()) && "N".equals(resourcesConfigs.get(i).getIsLive()) ){
					Short type = 0;
					String resourcesURL = null;
					String version = null;
					String resourcesName = null;
					Integer reid = resourcesConfigs.get(i).getResourcesId();//资源ID
					if( reid != null ){					
						type = resourcesService.queryResourcesById(resourcesConfigs.get(i).getResourcesId()).getType();//资源类型
						resourcesURL = resourcesService.queryResourcesById(resourcesConfigs.get(i).getResourcesId()).getPath();
						version = resourcesService.queryResourcesById(resourcesConfigs.get(i).getResourcesId()).getVersion();
						if( type==0 ){					
							resourcesName = resourcesService.queryResourcesById(resourcesConfigs.get(i).getResourcesId()).getName();
						}else{
							resourcesName = null;
						}
						if( StrUtil.isNull(version) ){
							version = null;
						}
					}
					Short order = resourcesConfigs.get(i).getDisplayOrder();
					Timestamp begin = resourcesConfigs.get(i).getActionDate();//开始时间
					Timestamp end = resourcesConfigs.get(i).getEndDate();//结束时间
					Integer week = resourcesConfigs.get(i).getWeek();
					Integer seconds = resourcesConfigs.get(i).getSeconds();
					//隐藏Timestamp的毫秒，转化为String类型
					SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");   
					String beginStr = df.format(begin);  
					String endStr = df.format(end);
					pw.print(reid+"|");
					pw.print(type+"|");
					pw.print(resourcesName+"|");
					pw.print(resourcesURL+"|");
					pw.print(version+"|");
					pw.print(beginStr+"|");
					pw.print(endStr+"|");
					pw.print(order+"|");
					pw.print(week+"|");
					pw.print(seconds);
					pw.print("&nextline&");
					pw.println();
				}
				
			}		
			pw.close();
			String listUrl = PropertyUtil.configProperty.getProperty("resource_http_base_path") + "/" + 
					PropertyUtil.configProperty.getProperty("resource_ConfigListTxt") 
					+ "/" + configListId + ".txt";
			configList.setListUrl(listUrl);
			configList.setIsGenerationTxt((short)1);
			configListService.saveConfigList(configList);
			flag = "succ";
		} catch (IOException e) {
			flag = "fail";
			e.printStackTrace();
		}
		return flag;
	}
	
	// add by hxh 20160517
	public String generateXml(Integer configListId){
		String flag = null;
		TbConfigList configList = configListService.queryConfigListById(configListId);
		List<TbResourcesConfig> resourcesConfigs = resourcesConfigService.queryResourcesConfigByConfigListId(configListId);
		
	       // 建立document对象 
	       Document document = DocumentHelper.createDocument();

	       // 创建根节点
	       Element root = DocumentHelper.createElement("AllConfigureRecord");
	       document.setRootElement(root);
	       
	       //Element root = document.addElement("AllConfigureRecord");
	       // 加入一行注释 
	       //root.addComment("This is a test for dom4j, holen, 2004.9.11");
	       
	       // 加入属性内容
/*	       root.addAttribute("Id","92");
	       root.addAttribute("name","出厂配置（驯龙广告片）");
	       root.addAttribute("isEnable","1");*/
	       root.addAttribute("Id",String.valueOf(configList.getId()));
	       root.addAttribute("name",configList.getName());
	       root.addAttribute("isEnable",String.valueOf(configList.getIsEnable()));
	       
		   //第一行为列表的资源数量
		   int iReCount=resourcesConfigs.size();
		   root.addAttribute("iReCount",String.valueOf(iReCount));
		   
	       for(int i=0;i<iReCount;i++){
		       // 加入第i个节点 
		       Element node = root.addElement("ConfigureRecord");
				Short type = 0;
				String resourcesURL = null;
				String version = null;
				String resourcesName = null;
				Integer reid = resourcesConfigs.get(i).getResourcesId();//资源ID
				if( reid != null ){					
					type = resourcesService.queryResourcesById(resourcesConfigs.get(i).getResourcesId()).getType();//资源类型
					resourcesURL = resourcesService.queryResourcesById(resourcesConfigs.get(i).getResourcesId()).getPath();
					version = resourcesService.queryResourcesById(resourcesConfigs.get(i).getResourcesId()).getVersion();
					if( type==0 ){					
						resourcesName = resourcesService.queryResourcesById(resourcesConfigs.get(i).getResourcesId()).getName();
					}else{
						resourcesName = null;
					}
					if( StrUtil.isNull(version) ){
						version = null;
					}
				}
				
				Short order = resourcesConfigs.get(i).getDisplayOrder();
				Timestamp begin = resourcesConfigs.get(i).getActionDate();//开始时间
				Timestamp end = resourcesConfigs.get(i).getEndDate();//结束时间
				Integer week = resourcesConfigs.get(i).getWeek();
				Integer seconds = resourcesConfigs.get(i).getSeconds();
				//隐藏Timestamp的毫秒，转化为String类型
				SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");   
				String beginStr = df.format(begin);  
				String endStr = df.format(end);
				
		       // 加入属性内容
		       node.addAttribute("resourceId",String.valueOf(reid));
		       node.addAttribute("resourceType",String.valueOf(type));
		       node.addAttribute("appName",String.valueOf(resourcesName));
		       node.addAttribute("URL",String.valueOf(resourcesURL));
		       node.addAttribute("version",String.valueOf(version));
		       node.addAttribute("startTime",beginStr);
		       node.addAttribute("stopTime",endStr);
		       node.addAttribute("orderNumber",String.valueOf(order));
		       node.addAttribute("weekday",String.valueOf(week));
		       node.addAttribute("showTime",String.valueOf(seconds));
	       }

		try {
			String path = PropertyUtil.configProperty.getProperty("resource_disk_base_path") + File.separator + PropertyUtil.configProperty.getProperty("resource_ConfigListTxt");
			File dir = new File(path);
			if (!dir.exists()) {
				dir.mkdirs();
			}
			String filename=path + File.separator + configListId + ".xml";
			File file = new File(filename);
			if (!file.exists()) {
				file.createNewFile();
			}else{
				file.delete();
			}
			// 将document中的内容写入文件中
			OutputFormat format = OutputFormat.createPrettyPrint();
			format.setEncoding("UTF-8");
			XMLWriter writer = new XMLWriter(new FileOutputStream(filename),format);
			writer.write(document);
			writer.close();
			flag = "succ";
		} catch (IOException e) {
			flag = "fail";
			e.printStackTrace();
		}
		return flag;
	}
	
	/**
	 * 接口
	 * @param request
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value="/generateXmlByconfigListId",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String generateXmlByconfigListId( HttpServletRequest request ) throws UnsupportedEncodingException{
		Integer configListId = 0;
		String para=request.getParameter("configListId");
        if(para!=null){
        	configListId = Integer.parseInt(para);
        }
		if(configListId==0){
			List<TbConfigList> configLists=configListService.queryAll();
			String ids="";
			for(int i=0;i<configLists.size();i++){
				Integer Id=configLists.get(i).getId();
				String flag=generateXml(Id);
				ids+=String.valueOf(Id);
				if(i<configLists.size()-1){
					ids+=",";
				}
			}
			return String.valueOf(ids);
		}
		String flag=generateXml(configListId);
        return flag;
	}
	
}

